<template>
    <div class="production-filter">
        <el-checkbox-group v-model="productionStatus">
            <el-checkbox label="待生产" value="waiting" />
            <el-checkbox label="生产中" value="producing" />
            <el-checkbox label="已完成" value="finished" />
        </el-checkbox-group>
    </div>
    <div class="production-content" style="width: 100%; height: calc(100vh - 180px)">
        <el-auto-resizer>
            <template #default="{ height }">
                <el-scrollbar :height="height">
                    <el-descriptions title="数据列表" :column="5" border>
                        <template #extra>
                            <el-text type="warning" tag="b">当前有{{ total }}条数据</el-text>
                        </template>
                        <div v-for="(item, index) in productionList" :key="index">
                            <!-- 产品名称 -->
                            <el-descriptions-item>
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><BrandProducthunt /></el-icon>
                                        产品名称
                                    </div>
                                </template>
                                <el-text tag="b" type="primary">
                                    {{ item.purchaseId.productName }}<el-text type="warning"> * {{ item.purchaseId.purchaseNumber }}只</el-text>
                                </el-text>
                            </el-descriptions-item>
                            <!-- 面纸尺寸 -->
                            <el-descriptions-item>
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><BrandProducthunt /></el-icon>
                                        面纸尺寸
                                    </div>
                                </template>
                                <el-text tag="b" type="primary">
                                    {{ item.purchaseId.tissueSize == '' ? '/' : item.purchaseId.tissueSize }}
                                </el-text>
                            </el-descriptions-item>
                            <!-- 瓦楞尺寸 -->
                            <el-descriptions-item>
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><BrandProducthunt /></el-icon>
                                        瓦楞尺寸
                                    </div>
                                </template>
                                <el-text tag="b" type="primary">
                                    {{ item.purchaseId.corrugatedSize == '' ? '/' : item.purchaseId.corrugatedSize }}
                                </el-text>
                            </el-descriptions-item>
                            <!-- 订单状态 -->
                            <el-descriptions-item>
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><StatusPartialFail /></el-icon>
                                        订单状态
                                    </div>
                                </template>
                                <el-text tag="b" :type="item.purchaseId.orderStatus">
                                    {{ matchOrderStatus(item.purchaseId.orderStatus) }}
                                </el-text>
                            </el-descriptions-item>
                            <!-- 送货日期 -->
                            <el-descriptions-item>
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><StatusPartialFail /></el-icon>
                                        送货日期
                                    </div>
                                </template>
                                <b :class="matchOrderRemainingDeliveryTime(item.purchaseId.orderDeliveryDate)">
                                    {{
                                        item.purchaseId.orderDeliveryDate == '暂无送货计划'
                                            ? '暂无送货计划'
                                            : formatTimeZone(item.purchaseId.orderDeliveryDate as unknown as Date, 'YYYY-MM-DD')
                                    }}
                                </b>
                            </el-descriptions-item>
                            <!-- 生产数量 -->
                            <el-descriptions-item :span="2" v-if="item.productionStatus == 'finished'">
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><Production24Regular /></el-icon>
                                        生产数量
                                    </div>
                                </template>
                                <div class="flex gap-2">
                                    <el-input-number v-model="item.productionNumber" :step="1" step-strictly></el-input-number>
                                    <el-button type="primary" @click="updateProductionNumberEvent(item)">修改</el-button>
                                </div>
                            </el-descriptions-item>
                            <!-- 生产操作 -->
                            <el-descriptions-item :span="2" v-if="item.productionStatus == 'waiting' || item.productionStatus == 'producing'">
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><Production24Regular /></el-icon>
                                        生产操作
                                    </div>
                                </template>
                                <!-- 待生产 -->
                                <el-button
                                    v-if="item.productionStatus == 'waiting'"
                                    plain
                                    type="success"
                                    :icon="ArrowBigRightLine"
                                    @click="confirmProductionEvent(item)"
                                >
                                    确认生产
                                </el-button>
                                <!-- 生产中 -->
                                <el-button
                                    v-if="item.productionStatus == 'producing'"
                                    plain
                                    :icon="ArrowBigLeftLine"
                                    type="warning"
                                    @click="cancelProductionEvent(item)"
                                >
                                    取消生产
                                </el-button>
                                <el-button
                                    v-if="item.productionStatus == 'producing'"
                                    plain
                                    @click="
                                        showProductDesign(
                                            item.purchaseId._id,
                                            item.purchaseId.customerId,
                                            item.purchaseId.productId,
                                            item.purchaseId.orderNumber,
                                            item.purchaseId.purchaseNumber,
                                            item.purchaseId.orderDeliveryDate
                                        )
                                    "
                                    :icon="Eye24Regular"
                                >
                                    查看生产参数
                                </el-button>
                            </el-descriptions-item>
                            <!-- 流水操作 -->
                            <el-descriptions-item :span="3">
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><Sitemap /></el-icon>
                                        流水操作
                                    </div>
                                </template>
                                <!-- 待生产 -->
                                <div v-if="item.productionStatus == 'waiting'">/</div>
                                <!-- 生产中 -->
                                <div v-if="item.productionStatus == 'producing'" class="flex items-center gap-2">
                                    <div class="flex items-center gap-2 border-dashed border-2 border-indigo-600 p-2">
                                        <el-radio-group v-model="item.nextProcess">
                                            <el-radio value="packinnerbox">内盒打包</el-radio>
                                            <el-radio value="warehouse">入仓库</el-radio>
                                        </el-radio-group>
                                        <el-input-number v-model="item.purchaseId.orderNumber" :step="1" step-strictly />
                                        <el-button plain type="success" :icon="HandRight24Regular" @click="dispatchProductionControlEvent(item)">
                                            确认下放
                                        </el-button>
                                    </div>
                                </div>
                                <!-- 已完成 -->
                                <div v-if="item.productionStatus == 'finished'">
                                    <el-text tag="b" type="info">
                                        已下放至【{{ item.pipeline == '仓库' ? item.pipeline : matchProductionType(item.pipeline) }}】
                                    </el-text>
                                    <el-button plain type="danger" :icon="ResetAlt" @click="resetProductionControlEvent(item)">撤销</el-button>
                                </div>
                            </el-descriptions-item>
                            <!-- 打印标签 -->
                            <el-descriptions-item :span="2" v-if="item.productionStatus == 'finished'">
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><Printer /></el-icon>
                                        打印标签
                                    </div>
                                </template>
                                <el-button plain type="success" :icon="Label" @click="printLabelEvent(item)">打印</el-button>
                            </el-descriptions-item>
                            <!-- 工艺 -->
                            <el-descriptions-item :span="2" v-if="item.productionStatus == 'waiting' || item.productionStatus == 'producing'">
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><PaintBrush /></el-icon>
                                        工艺
                                    </div>
                                </template>
                                <el-text tag="b" type="primary">{{ item.process }}</el-text>
                            </el-descriptions-item>
                            <!-- 订单备注 -->
                            <el-descriptions-item :span="3">
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><Information /></el-icon>
                                        订单备注
                                    </div>
                                </template>
                                <el-text tag="b" type="primary">{{ item.purchaseId.orderRemark }}</el-text>
                            </el-descriptions-item>
                            <!-- 操作工日志 -->
                            <el-descriptions-item :span="5">
                                <template #label>
                                    <div class="flex items-center">
                                        <el-icon class="el-icon--left"><FlowLogsVpc /></el-icon>
                                        操作工日志
                                    </div>
                                </template>
                                <el-input v-model="item.productionRemark" placeholder="请输入本次生产的日志" type="textarea" clearable></el-input>
                            </el-descriptions-item>
                        </div>
                    </el-descriptions>
                </el-scrollbar>
            </template>
        </el-auto-resizer>
    </div>
    <div class="production-pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            @change="handleSizeChange"
            :total="total"
            :page-sizes="[5, 10, 20, 50]"
            layout="prev, pager, next, sizes, jumper, total"
            background
        />
    </div>

    <!-- 查看生产单 -->
    <printProduction v-model:print-visible="printVisible" :print-btn-symbol="false" v-model:print-data="printData"></printProduction>
    <!-- 打印仓库标签 -->
    <printWarehouseLabel
        v-model:print-warehouse-label-visible="printWarehouseLabelVisible"
        v-model:print-warehouse-label-data="printWarehouseLabelData"
    />
</template>

<script setup lang="ts">
import { getProductInfo } from '@/api/product';
import { dispatchProductionControl, getProductionList, resetProductionControl, updateProduction, warehouseIn } from '@/api/production';
import { formatTimeZone } from '@utils/calculate';
import { StatusPartialFail, PaintBrush, Information, FlowLogsVpc, Printer, Label, ResetAlt } from '@vicons/carbon';
import { Production24Regular, Eye24Regular, HandRight24Regular } from '@vicons/fluent';
import { BrandProducthunt, Sitemap, ArrowBigRightLine, ArrowBigLeftLine } from '@vicons/tabler';

onMounted(() => {
    getProductionListEvent();
});

/* ******************************通用属性/方法****************************** */
// 三种生产状态
const productionStatus = ref<any[]>(['waiting', 'producing']);
// 展示数据
const productionList = ref<AjaxResponse['productionList']>([]);
// 获取生产列表
const getProductionListEvent = async () => {
    // 重置数据
    productionList.value.length = 0;
    total.value = 0;

    // 获取数据
    const result = await getProductionList('innerbox', productionStatus.value, currentPage.value, pageSize.value);
    // 加载数据
    total.value = result.total;
    for (let index = 0; index < result.data.length; index++) {
        const production = result.data[index];
        // 下一道工序
        production.nextProcess = '';
        // 加载对应产品的工艺
        const product = await getProductInfo(production.purchaseId.customerId, production.purchaseId.productId);
        production.process = '⭐工艺：' + product.data.process + '⭐描述：' + product.data.description;
        // 填充表单数据
        productionList.value.push(production);
    }
    // 排序
    productionList.value.sort((a) => (a.purchaseId.orderStatus == 'danger' ? -1 : 1));
};
// 监听生产状态变化
watch(productionStatus, () => {
    if (productionStatus.value.length == 0) {
        ElMessage.warning('请至少选择一个生产状态');
        productionList.value.length = 0;
        return;
    }
    getProductionListEvent();
});
// 修改生产数量
const updateProductionNumberEvent = (item: AjaxResponse['productionList'][number]) => {
    updateProduction(item._id, 'productionNumber', item.productionNumber).then((res) => {
        ElMessage.success(res.message);
        getProductionListEvent();
    });
};

/* ******************************分页属性/方法****************************** */
// 当前页
const currentPage = ref(1);
// 每页数量
const pageSize = ref(5);
// 总数
const total = ref(0);
// 监听分页变化
const handleSizeChange = () => {
    getProductionListEvent();
};

/* ******************************生产参数属性/方法****************************** */
// 确认生产
const confirmProductionEvent = (item: AjaxResponse['productionList'][number]) => {
    ElMessageBox.confirm('确定生产吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 确定生产
        updateProduction(item._id, 'productionStatus', 'producing').then((res) => {
            ElMessage.success(res.message);
            getProductionListEvent();
        });
    });
};
// 取消生产
const cancelProductionEvent = (item: AjaxResponse['productionList'][number]) => {
    ElMessageBox.confirm('确定取消生产吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 取消生产
        updateProduction(item._id, 'productionStatus', 'waiting').then((res) => {
            ElMessage.success(res.message);
            getProductionListEvent();
        });
    });
};
// 重置生产
const resetProductionControlEvent = (item: AjaxResponse['productionList'][number]) => {
    ElMessageBox.confirm('确定重置生产吗？将数据恢复至待生产的状态', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 重置生产
        resetProductionControl(item._id).then((res) => {
            ElMessage.success(res.message);
            getProductionListEvent();
        });
    });
};
// 下放任务 -- 下一道工序、入库
const dispatchProductionControlEvent = (item: AjaxResponse['productionList'][number]) => {
    if (item.nextProcess == '') {
        ElMessage.warning('请选择下放工序');
        return;
    }
    // 入仓库
    if (item.nextProcess == 'warehouse') {
        warehouseIn(
            item._id,
            item.purchaseId._id,
            item.purchaseId.orderNumber,
            item.productionRemark,
            item.purchaseId.customerId,
            item.purchaseId.productId
        ).then((res) => {
            ElMessage.success(res.message);
            getProductionListEvent();
        });
        return;
    }
    // 下放任务
    dispatchProductionControl(item._id, item.purchaseId._id, item.nextProcess, item.purchaseId.orderNumber, item.productionRemark).then((res) => {
        ElMessage.success(res.message);
        getProductionListEvent();
    });
};

/* ******************************图纸参数属性/方法****************************** */
// 展示图纸参数
const showProductDesign = (
    orderId: string,
    customerId: string,
    productId: string,
    orderNumber: number,
    purchaseNumber: number,
    orderDeliveryDate: Date | string
) => {
    printData[0] = { orderId, customerId, productId, orderNumber, purchaseNumber, orderDeliveryDate };
    printVisible.value = true;
};
// 查看图纸参数的dialog
const printVisible = ref(false);
// 查看必要的数据
const printData = reactive<
    { orderId: string; customerId: string; productId: string; orderNumber: number; purchaseNumber: number; orderDeliveryDate: Date | string }[]
>([]);

/* ******************************仓库标签属性/方法****************************** */
// 仓库标签弹窗是否可见
const printWarehouseLabelVisible = ref(false);
// 仓库标签打印数据
const printWarehouseLabelData = reactive<{
    customerAbbreviation: string;
    productName: string;
    productSize: string;
    orderNo: string;
    orderNumber: number;
    productionNumber: number;
}>({
    customerAbbreviation: '',
    productName: '',
    productSize: '',
    orderNo: '',
    orderNumber: 0,
    productionNumber: 0,
});
// 打印标签
const printLabelEvent = (item: AjaxResponse['productionList'][number]) => {
    printWarehouseLabelData.customerAbbreviation = item.purchaseId.customerAbbreviation;
    printWarehouseLabelData.productName = item.purchaseId.productName;
    printWarehouseLabelData.productSize = item.purchaseId.productSize;
    printWarehouseLabelData.orderNo = item.purchaseId.orderNo;
    printWarehouseLabelData.orderNumber = item.purchaseId.orderNumber;
    printWarehouseLabelData.productionNumber = item.productionNumber;
    printWarehouseLabelVisible.value = true;
};

/* ******************************工具属性/方法****************************** */
// 匹配订单状态
const matchOrderStatus = (status: 'primary' | 'warning' | 'danger') => {
    let obj = {
        primary: '正常',
        warning: '加急',
        danger: '特急',
    };
    return obj[status];
};
// 匹配订单剩余送货时间
const matchOrderRemainingDeliveryTime = (time: string) => {
    // 暂无送货计划
    if (time == '暂无送货计划') {
        return 'text-gray-500';
    }
    // 剩余送货时间
    const remainingDeliveryTime = new Date(time).getTime() - new Date().getTime();
    // 剩余送货时间小于24小时，显示红色
    if (remainingDeliveryTime < 24 * 60 * 60 * 1000) {
        return 'text-red-500';
    }
    // 剩余送货时间小于48小时，显示橙色
    if (remainingDeliveryTime < 48 * 60 * 60 * 1000) {
        return 'text-orange-500';
    }
    // 剩余送货时间大于48小时，显示绿色
    return 'text-green-500';
};

// 匹配生产工艺
const matchProductionType = (type: string) => {
    let obj = {
        outerbox: '外箱生产',
        packouterbox: '外箱打包',
        diecutting: '模切生产',
        backing: '裱瓦生产',
        innerbox: '内盒生产',
        packinnerbox: '内盒打包',
    };
    return obj[type];
};
</script>

<style scoped lang="scss">
.production-filter {
    height: 50px;
    display: flex;
    align-items: center;
}
.production-pagination {
    height: 50px;
    display: flex;
    align-items: center;
}
</style>
